package com.orhon.smartcampus.modules.base.fetcher;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.PeriodsDao;
import com.orhon.smartcampus.modules.base.dao.TextbooksDao;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.entity.Textbooks;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPeriod;
import com.orhon.smartcampus.modules.base.gqlModel.GQLTextbooks;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.PeriodMapper;
import com.orhon.smartcampus.modules.base.mm.TextbookMapper;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.Util;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class TextbooksFetcher implements DataFetcher {

    @Autowired
    TextbooksDao textbooksDao;

    @Override
    public Object get(DataFetchingEnvironment env) throws Exception {        
        List<GQLTextbooks> gqlTextbooks = new ArrayList<>();


        GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);
        String hql = "from Textbooks where deleted_at = null ";
        if(env.containsArgument("condition")) {
            HashMap<String,Object> map = ObjectToMap.to(env.getArgument("condition"));
            if(map.get("periodId")!=null) {
                hql += " and period_id "+ Util.decide(map.get("periodId"));
            }
            if(map.get("subjectId")!=null) {
                hql += " and subject_id "+ Util.decide(map.get("subjectId"));
            }
        }
        List<Textbooks> list = textbooksDao.find(hql,null,page.getPage(),page.getLimit());
        for (Textbooks item : list) {
            GQLTextbooks textbooks = TextbookMapper.MAPPER.toTextbook(item);
            gqlTextbooks.add(textbooks);
        }
        Long total = 0L;
        if (env.getSelectionSet().contains("total")){
        	 total = textbooksDao.getTotalCount(hql);
        }
        return Result.ok().put("data", gqlTextbooks).put("total", total);
    }


}
